package com.qhhc.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;

import com.qhhc.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;

@Service
public class OSSService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSConfig ossConfig;

    /**
     * 上传文件到OSS并返回可访问的URL
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取文件原始名称
        String originalFilename = file.getOriginalFilename();

        // 生成唯一的文件名
        String fileName = UUID.randomUUID().toString();
        if (originalFilename != null && originalFilename.lastIndexOf(".") > 0) {
            fileName += originalFilename.substring(originalFilename.lastIndexOf("."));
        } else {
            fileName += ".wav"; // 默认为wav格式
        }

        // 使用临时文件作为中转
        Path tempFile = Files.createTempFile("upload_", fileName);
        file.transferTo(tempFile.toFile());

        // 设置OSS对象键名（文件路径）
        String objectName = "audio/" + fileName;

        // 创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(), objectName, tempFile.toFile());

        // 上传文件
        ossClient.putObject(putObjectRequest);

        // 删除临时文件
        Files.delete(tempFile);

        // 返回文件访问URL
        return String.format("https://%s.%s/%s",
                ossConfig.getBucketName(),
                ossConfig.getEndpoint(),
                objectName);
    }

    /**
     * 上传本地文件到OSS并返回可访问的URL
     */
    public String uploadLocalFile(String localFilePath) throws IOException {
        File localFile = new File(localFilePath);
        if (!localFile.exists()) {
            throw new IOException("本地文件不存在: " + localFilePath);
        }

        // 生成唯一的文件名
        String originalFilename = localFile.getName();
        String fileName = UUID.randomUUID().toString();
        if (originalFilename.lastIndexOf(".") > 0) {
            fileName += originalFilename.substring(originalFilename.lastIndexOf("."));
        } else {
            fileName += ".wav"; // 默认为wav格式
        }

        // 设置OSS对象键名（文件路径）
        String objectName = "audio/" + fileName;

        // 创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(), objectName, localFile);

        // 上传文件
        ossClient.putObject(putObjectRequest);

        // 返回文件访问URL
        return String.format("https://%s.%s/%s",
                ossConfig.getBucketName(),
                ossConfig.getEndpoint(),
                objectName);
    }
}